package school.community.controller;

import school.community.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class AdminLoginController {

  @GetMapping("/admin")
  public String admin(Model model) {
//    model.addAttribute("tags","admin");
    return "adminLogin";
  }

  @RequestMapping("/admin/login")
  public String login(@RequestParam("username") String username,
                      @RequestParam("password") String password,
                      Model model,
                      HttpSession session,
                      HttpServletResponse response) {

    //从数据库种查管理员信息
    User admin = User.builder()
            .id(3L)
            .accountId("admin")
            .avatarUrl("https://s1.ax1x.com/2020/06/13/tvLoQ0.png")
            .name("admin")
            .gmtCreate(1592049916874L)
            .gmtModified(System.currentTimeMillis())
            .token("7e1b4d45-cfad-46db-9b95-d3ef55333632")
            .build();
    if (admin.getName().equals(username) && admin.getAccountId().equals(password)) {
      String token = admin.getToken();
      Cookie cookie = new Cookie("token", token);
      cookie.setMaxAge(60 * 60 * 24 * 30 * 6);
      response.addCookie(cookie);
      model.addAttribute("identity","admin");
      session.setAttribute("user",admin);
      session.setAttribute("admin",admin);
      //登录成功：重定向到/main.html页面
//      return "/";
      return "redirect:/";
    } else {
      model.addAttribute("msg", "用户名或者密码错误");
      return "adminLogin";
    }
  }

  //注销登录
  @RequestMapping("/admin/loginOut")
  public String loginOut(HttpSession session){
    //移除session
    session.invalidate();
    return "redirect:/";
  }
}



